﻿namespace VolumeFileExaminer
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Windows.Forms;
    using SinclairCC.AppV;

    public partial class MainForm : Form
    {
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        private struct SHFILEINFO {
            public IntPtr hIcon;
            public int iIcon;
            public uint dwAttributes;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szDisplayName;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szTypeName;
        }

        [DllImport("shell32.dll", CharSet=CharSet.Auto)]
        private static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbFileInfo, SHGFI uFlags);

        [Flags]
        enum SHGFI : int
        {
            /// <summary>get icon</summary>
            Icon = 0x000000100,
            /// <summary>get display name</summary>
            DisplayName = 0x000000200,
            /// <summary>get type name</summary>
            TypeName = 0x000000400,
            /// <summary>get attributes</summary>
            Attributes = 0x000000800,
            /// <summary>get icon location</summary>
            IconLocation = 0x000001000,
            /// <summary>return exe type</summary>
            ExeType = 0x000002000,
            /// <summary>get system icon index</summary>
            SysIconIndex = 0x000004000,
            /// <summary>put a link overlay on icon</summary>
            LinkOverlay = 0x000008000,
            /// <summary>show icon in selected state</summary>
            Selected = 0x000010000,
            /// <summary>get only specified attributes</summary>
            Attr_Specified = 0x000020000,
            /// <summary>get large icon</summary>
            LargeIcon = 0x000000000,
            /// <summary>get small icon</summary>
            SmallIcon = 0x000000001,
            /// <summary>get open icon</summary>
            OpenIcon = 0x000000002,
            /// <summary>get shell size icon</summary>
            ShellIconSize = 0x000000004,
            /// <summary>pszPath is a pidl</summary>
            PIDL = 0x000000008,
            /// <summary>use passed dwFileAttribute</summary>
            UseFileAttributes = 0x000000010,
            /// <summary>apply the appropriate overlays</summary>
            AddOverlays = 0x000000020,
            /// <summary>Get the index of the overlay in the upper 8 bits of the iIcon</summary>
            OverlayIndex = 0x000000040,
        } 
        
        private VolumeFile volumeFile;

        public MainForm()
        {
            InitializeComponent();
#if DEBUG
            this.WindowState = FormWindowState.Maximized;
#endif
        }

        private void ClickOpenVolumeMenuItem(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.CheckFileExists = true;
            ofd.Filter = "PKG File|*.pkg";
            ofd.Multiselect = false;
            ofd.Title = "Select an volume file to examine.";
            if (ofd.ShowDialog(this) == DialogResult.OK)
            {
                LoadVolumeFile(ofd.FileName);
                this.packageHistoryToolStripMenuItem.Enabled = true;
                this.closeToolStripMenuItem.Enabled = true;
            }
        }

        private void LoadVolumeFile(string filePath)
        {
            this.CloseVolumeFile();

            this.volumeFile = new VolumeFile(filePath);
            
            this.fileSystemTree.Nodes.Clear();

            foreach (_DIRECTORY_STRUCT_PRIMARY childDir in this.volumeFile.GetRootDirectories()) // this.rootDirectory.ChildDirectories)
            {
                TreeNode rootNode = this.fileSystemTree.Nodes.Add(childDir.LongName);
                rootNode.Tag = childDir.ContainerIndex;

                if (this.volumeFile.GetChildContainers(childDir.ContainerIndex).Length > 0)
                {
                    rootNode.Nodes.Clear();
                    rootNode.Nodes.Add("_dummy");
                }
                //LoadChildNodes(rootNode/*, childDir.ContainerIndex*/);
                rootNode.Expand();
            }

            /*
            // Load virtual registry data from osguard.cp.
            Guid osGuardFileGuid = this.volumeFile.CompressedIndex.FindOSGuardFileGuid();
            DirectoryMapEntry osGuardMapEntry = this.volumeFile.CompressedIndex.DirectoryEntries[osGuardFileGuid];
            string tempOsGuardFilePath = System.IO.Path.GetTempFileName();
            this.volumeFile.ExportDirectoryEntry(osGuardMapEntry, tempOsGuardFilePath);
            CpFile osGuardFile = new CpFile(tempOsGuardFilePath);
            foreach (VirtualRegistryEntry entry in osGuardFile.VirtualRegistry.ObjectList)
            {
                if (entry.EntrySize > 0)
                {
                    string[] entryParts = entry.Name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);

                    TreeNodeCollection nodeCollection = this.registryTree.Nodes;
                    for (int i = 0; i < entryParts.Length; i++)
                    {
                        nodeCollection = AddRegistryTreeNode(nodeCollection, entryParts[i], entry);
                    }
                }
            }
            foreach (TreeNode node in this.registryTree.Nodes)
            {
                node.Expand();
            }

            try
            {
                System.IO.File.Delete(tempOsGuardFilePath);
            }
            catch (Exception ex)
            {
                if (!((ex is ArgumentException) || (ex is ArgumentNullException) || (ex is System.IO.DirectoryNotFoundException) || (ex is System.IO.IOException)
                     || (ex is NotSupportedException) || (ex is System.IO.PathTooLongException) || (ex is UnauthorizedAccessException)))
                {
                    throw;
                }
            }
            */
        }

        private void RegistryTreeBeforeSelect(object sender, TreeViewCancelEventArgs e)
        {
            VirtualRegistryEntry entry = e.Node.Tag as VirtualRegistryEntry;
            if (entry == null) return;

            this.regValuesListView.BeginUpdate();
            this.regValuesListView.Items.Clear();

            if ((entry.Attributes & RegistryEntryAttributes.HasValue) == RegistryEntryAttributes.HasValue)
            {
                ListViewItem newItem = new ListViewItem("(Default)");
                newItem.SubItems.Add(entry.ValueTypeAsWindowsString);
                newItem.SubItems.Add(entry.Value.ToString());
                this.regValuesListView.Items.Add(newItem);
            }

            foreach (VirtualRegistryEntry valueEntry in entry.ChildEntries)
            {
                ListViewItem newItem = new ListViewItem(valueEntry.Name);
                newItem.SubItems.Add(valueEntry.ValueTypeAsWindowsString);
                newItem.SubItems.Add(valueEntry.Value.ToString());
                this.regValuesListView.Items.Add(newItem);
            }


            foreach (ColumnHeader clm in this.regValuesListView.Columns)
            {
                clm.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
                int headerWidth = clm.Width;
                clm.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
                int columnWidth = clm.Width;
                clm.Width = Math.Max(headerWidth, columnWidth);
            }


            this.regValuesListView.EndUpdate();
        }

        private TreeNodeCollection AddRegistryTreeNode(TreeNodeCollection parentNodeCollection, string name, VirtualRegistryEntry entry)
        {
            if (!parentNodeCollection.ContainsKey(name))
            {
                TreeNode newNode = parentNodeCollection.Add(name, name);
                newNode.Tag = entry;
                newNode.ImageKey = "folderopen";
                newNode.SelectedImageKey = "folderopen";
                newNode.StateImageKey = "folderopen";
                return newNode.Nodes;
            }
            else
            {
                return parentNodeCollection[name].Nodes;
            }
        }


        private void BeforeFileSystemTreeExpand(object sender, TreeViewCancelEventArgs e)
        {
            //e.Node.Nodes.Clear();
            uint containerIndex = (uint)e.Node.Tag;
            LoadChildNodes(e.Node/*, containerIndex*/);
        }

        private void DisplayChildContainers(uint parentIndex)
        {
//            foreach (Container c in containerTable)
//            {
//                if (c.Header.ContainerIndex == parentIndex)
//                {
                    /*
                    Console.WriteLine("flush index: {0,10:N0}\tindex: {1:N0}", c.Header.ContainerFlushIndex, c.Header.ContainerIndex);
                    Console.WriteLine("info data length: {0:N0}", c.Header.InfoDataLength);
                    Console.WriteLine("metadata index: {0:N0}", c.Header.MetadataIndex);
                    Console.WriteLine("package data index: {0:N0}", c.Header.PackageDataIndex);
                    Console.WriteLine("package ID: {0:N0}", c.Header.PackageID);
                    Console.WriteLine("parent directory ID: {0:N0}", c.Header.PrimaryDirectoryID);
                    Console.WriteLine();
                    Console.WriteLine();
                    */
//                }
//            }
        }


        private void LoadChildNodes(TreeNode parentTreeNode/*, uint parentContainerIndex*/)
        {
            parentTreeNode.TreeView.BeginUpdate();

            /*
            SinclairCC.AppV.Container parentContainer = (SinclairCC.AppV.Container)parentTreeNode.Tag;
            */
            uint containerIndex = (uint)parentTreeNode.Tag;
            SinclairCC.AppV.Container[] childContainers = this.volumeFile.GetChildContainers(containerIndex);

            parentTreeNode.Nodes.Clear();
            foreach (SinclairCC.AppV.Container container in childContainers)
            {
                switch (container.Header.TypeId)
                {
                    case ContainerType.RUN_DIRECTORY:
                    case ContainerType.PACKAGE_DIRECTORY:
                        NonRootDirectoryContainer nonRootDir = (NonRootDirectoryContainer)container;
                        foreach (_DIRECTORY_STRUCT_PRIMARY childDir in nonRootDir.ChildDirectories)
                        {
                            // childDir.ContainerIndex, (System.IO.FileAttributes)childDir.Attributes);
                            TreeNode childNode = parentTreeNode.Nodes.Add(childDir.LongName);
                            childNode.Tag = childDir.ContainerIndex; // container.Header.ContainerIndex;
                            //this.DisplayChildContainers(childDir.ContainerIndex, indent);

                            if (((System.IO.FileAttributes)childDir.Attributes & System.IO.FileAttributes.Directory) == System.IO.FileAttributes.Directory)
                            {
                                this.LoadFolderIconIntoImageList();
                                childNode.ImageKey = "folder";
                                childNode.StateImageKey = "folder";
                                childNode.SelectedImageKey = "folder";

                                if (this.volumeFile.GetChildContainers(childDir.ContainerIndex).Length > 0)
                                {
                                    childNode.Nodes.Clear();
                                    childNode.Nodes.Add("_dummy");
                                }
                            }
                            else
                            {
                                string extension = System.IO.Path.GetExtension(childDir.LongName);
                                if (extension.Length > 0)
                                {
                                    this.LoadIconIntoImageList(childDir.LongName);
                                    childNode.ImageKey = extension;
                                    childNode.StateImageKey = extension;
                                    childNode.SelectedImageKey = extension;
                                }
                                else
                                { // TODO: What if the extension is zero length?
                                }
                            }

#if DEBUG
                            childNode.Expand();
#endif
                        }
                        break;
                    /*
                    case ContainerType.CONTAINER_PACKAGE:
                        PackageContainer contPack = (PackageContainer)c;
                        Console.WriteLine("{0}{1}", new string(' ', indent * 3), "CONTAINER_PACKAGE");
                        break;

                    case ContainerType.RUN_FILE:
                        RunFileContainer runfileCont = (RunFileContainer)c;
                        Console.WriteLine("{0}{1}", new string(' ', indent * 3), "RUN_FILE");
                        break;

                    case ContainerType.PACKAGE_FILE:
                        PackageFileContainer pkgFileCont = (PackageFileContainer)c;
                        Console.WriteLine("{0}{1}", new string(' ', indent * 3), "PACKAGE_FILE");
                        break;

                    case ContainerType.CONTAINER_EMPTY:
                        Console.WriteLine("{0}{1}", new string(' ', indent * 3), "CONTAINER_EMPTY");
                        break;

                    default:
                        // TODO: Do something with "other" container types.
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.Write("Unhandled container type: ");
                        Console.Write(c.Header.TypeId);
                        Console.WriteLine(".");
                        break;
                    */
                }


                //Icon largeIcon = Icon.ExtractAssociatedIcon(entry.LongFileName);

                /*
Dim BigIcon As Icon = Nothing 
    BigIcon = Icon.ExtractAssociatedIcon("c:\zebra.zip") 
    Dim largeimages As New ImageList 
    Dim smallimages As New ImageList 
 
    largeimages.Images.Add("1", BigIcon) 
 
    'Fix a smaller version with interpolation 
    Dim bm As New Bitmap(BigIcon.ToBitmap) 
    Dim thumb As New Bitmap(16, 16) 
    Dim g As Graphics = Graphics.FromImage(thumb) 
    g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic 
    g.DrawImage(bm, New Rectangle(0, 0, 16, 16), New Rectangle(0, 0, bm.Width, bm.Height), GraphicsUnit.Pixel) 
    g.Dispose() 
    bm.Dispose() 
    smallimages.Images.Add("1", thumb) 
    ListView1.SmallImageList = smallimages 
    ListView1.LargeImageList = largeimages 
    thumb.Dispose() 
    ListView1.Items.Add("Test", "Test", "1") 
                */

                //LoadChildNodes(childNode, entry);
            }

            //parentTreeNode.TreeView.Sort();
            parentTreeNode.TreeView.EndUpdate();
        }

        /// <summary>
        /// This function handles the Load event for the form.
        /// </summary>
        /// <param name="sender">The form being loaded.</param>
        /// <param name="e">Data specific to the event.</param>
        private void LoadForm(object sender, EventArgs e)
        {
            ClearDetailsControls();

#if DEBUG
            string filePath = System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"PKG Files\pidgin.pkg");
            //string filePath = System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"PKG Files\Adobe Reader.pkg");
            
            LoadVolumeFile(filePath);
            this.packageHistoryToolStripMenuItem.Enabled = true;
            this.closeToolStripMenuItem.Enabled = true;
#endif
        }


        private void LoadFolderIconIntoImageList()
        {
            // If the image list already contains an image for this extension, quit this function.
            if (iconImages.Images.ContainsKey("folder"))
                return;

            IntPtr smallIconPtr = IntPtr.Zero;
            SHFILEINFO shInfo = new SHFILEINFO();

            // Get the small icon for the specified file.
            smallIconPtr = SHGetFileInfo(System.Environment.GetFolderPath(Environment.SpecialFolder.System), (uint)System.IO.FileAttributes.Directory, ref shInfo, (uint)Marshal.SizeOf(shInfo), SHGFI.Icon | SHGFI.SmallIcon | SHGFI.UseFileAttributes);

            /*
shinfo.szDisplayName = New String(Chr(0), 260)
shinfo.szTypeName = New String(Chr(0), 80)
            */

            Icon ico = System.Drawing.Icon.FromHandle(shInfo.hIcon);
            iconImages.Images.Add("folder", ico);
        }
            

        private void LoadIconIntoImageList(string fileName)
        {
            string extension = System.IO.Path.GetExtension(fileName);

            // If the image list already contains an image for this extension, quit this function.
            if (iconImages.Images.ContainsKey(extension))
                return;

            IntPtr smallIconPtr = IntPtr.Zero;
            SHFILEINFO shInfo = new SHFILEINFO();

            // Get the small icon for the specified file.
            smallIconPtr = SHGetFileInfo(fileName, 0, ref shInfo, (uint)Marshal.SizeOf(shInfo), SHGFI.Icon | SHGFI.SmallIcon | SHGFI.UseFileAttributes);

            /*
shinfo.szDisplayName = New String(Chr(0), 260)
shinfo.szTypeName = New String(Chr(0), 80)
            */

            Icon ico = System.Drawing.Icon.FromHandle(shInfo.hIcon);
            iconImages.Images.Add(extension, ico);
        }
            

        private void FileSystemTreeMouseUp(object sender, MouseEventArgs e)
        {
            TreeView tree = sender as TreeView;
            if (tree != null)
            {
                TreeViewHitTestInfo hitTestInfo = tree.HitTest(e.Location);
                if (hitTestInfo.Node == null)
                {
                    tree.SelectedNode = null;
                    ClearDetailsControls();
                }
                else
                {
                    if (!hitTestInfo.Node.Bounds.Contains(e.Location))
                    {
                        tree.SelectedNode = null;
                        ClearDetailsControls();
                    }
                }
            }
        }

        private void ClearDetailsControls()
        {
            this.exportToolStripMenuItem.Enabled = false;

            this.fileNameLabel.Text = string.Empty;
            this.fileSizeLabel.Text = string.Empty;
            this.fileVersionLabel.Text = string.Empty;
            this.fileCreationDateLabel.Text = string.Empty;
            this.fileModificationDateLabel.Text = string.Empty;
            this.numberOfBlocksLabel.Text = string.Empty;
            this.featureBlockLabel.Text = string.Empty;
            this.compressionRatioLabel.Text = string.Empty;

            this.appConfigCheckBox.Checked = false;
            this.appDataCheckBox.Checked = false;
            this.overrideCheckBox.Checked = false;
            this.permanentCheckBox.Checked = false;
            this.userConfigCheckBox.Checked = false;
            this.userConfigCheckBox.Checked = false;

            this.archiveCheckBox.Checked = false;
            this.readOnlyCheckBox.Checked = false;
            this.hiddenCheckBox.Checked = false;
            this.systemCheckBox.Checked = false;

            this.blockMapListView.SuspendLayout();
            this.blockMapListView.Items.Clear();
            this.blockMapListView.ResumeLayout();

            this.regValuesListView.BeginUpdate();
            this.regValuesListView.Items.Clear();
            this.regValuesListView.EndUpdate();

            this.registryTree.BeginUpdate();
            this.registryTree.Nodes.Clear();
            this.registryTree.EndUpdate();
        }

        private void AfterFileSystemTreeNodeSelect(object sender, TreeViewEventArgs e)
        {
            /*
            DirectoryMapEntry entry = e.Node.Tag as DirectoryMapEntry;
            if (entry != null)
            {
                ClearDetailsControls();

                this.exportToolStripMenuItem.Enabled = true;

                this.fileNameLabel.Text = string.Format("{0} ({1})", entry.LongFileName, entry.ShortFileName);
                if (entry.EntryType == EntryType.File)
                {
                    this.fileSizeLabel.Text = FileSize.AutoFormat(entry.Size);
                }
                this.fileVersionLabel.Text = entry.Version.ToString();
                this.fileCreationDateLabel.Text = string.Format("{0:F} (local)", entry.CreationTimestamp.ToLocalTime());
                this.fileModificationDateLabel.Text = string.Format("{0:F} (local)", entry.ModificationTimestamp.ToLocalTime());

                this.archiveCheckBox.Checked = (entry.FileSystemAttributes & System.IO.FileAttributes.Archive) == System.IO.FileAttributes.Archive;
                this.readOnlyCheckBox.Checked = (entry.FileSystemAttributes & System.IO.FileAttributes.ReadOnly) == System.IO.FileAttributes.ReadOnly;
                this.hiddenCheckBox.Checked = (entry.FileSystemAttributes & System.IO.FileAttributes.Hidden) == System.IO.FileAttributes.Hidden;
                this.systemCheckBox.Checked = (entry.FileSystemAttributes & System.IO.FileAttributes.System) == System.IO.FileAttributes.System;

                this.appConfigCheckBox.Checked = (entry.AppVAttributes & AppVAttributes.ApplicationConfiguration) == AppVAttributes.ApplicationConfiguration;
                this.appDataCheckBox.Checked = (entry.AppVAttributes & AppVAttributes.ApplicationData) == AppVAttributes.ApplicationData;
                this.overrideCheckBox.Checked = (entry.AppVAttributes & AppVAttributes.Override) == AppVAttributes.Override;
                this.permanentCheckBox.Checked = (entry.AppVAttributes & AppVAttributes.Permanent) == AppVAttributes.Permanent;
                this.userConfigCheckBox.Checked = (entry.AppVAttributes & AppVAttributes.UserConfiguration) == AppVAttributes.UserConfiguration;
                this.userConfigCheckBox.Checked = (entry.AppVAttributes & AppVAttributes.UserData) == AppVAttributes.UserData;

                System.Collections.Generic.List<short> featureBlockNumbers = new System.Collections.Generic.List<short>();

                this.blockMapListView.SuspendLayout();
                this.blockMapListView.Items.Clear();
                BlockMapEntry blockMapEntry = this.volumeFile.BlockMap.GetBlockMapEntry(entry);
                if (blockMapEntry != null)
                {
                    this.numberOfBlocksLabel.Text = string.Format("{0}", blockMapEntry.DataBlockCount);
                    long totalCompressedSize = 0L;
                    long totalDecompressedSize = 0L;
                    for (int i = 0; i < blockMapEntry.Offsets.Length; i++)
                    {
                        ListViewItem newItem = new ListViewItem(string.Format("{0:N0}", i + 1));
                        newItem.SubItems.Add(ConvertToHexString(blockMapEntry.Offsets[i]));
                        DataBlock db = this.volumeFile.GetDataBlock(blockMapEntry.Offsets[i]);
                        newItem.SubItems.Add(string.Format("{0}", db.FeatureBlockNumber));
                        if (!featureBlockNumbers.Contains(db.FeatureBlockNumber))
                        {
                            featureBlockNumbers.Add(db.FeatureBlockNumber);
                        }
                        newItem.SubItems.Add(FileSize.AutoFormat(db.PhysicalDataSize));
                        totalCompressedSize += db.PhysicalDataSize;
                        newItem.SubItems.Add(FileSize.AutoFormat(db.DataSize));
                        totalDecompressedSize += db.DataSize;
                        this.blockMapListView.Items.Add(newItem);
                    }


                    float compressionRatio = 100F - (((float)totalCompressedSize / (float)totalDecompressedSize) * 100F);
                    this.compressionRatioLabel.Text = string.Format("{0:N2}%", compressionRatio);

                    if (compressionRatio > 0D)
                    {
                        this.fileSizeLabel.Text = string.Format("{0} compressed, {1} decompressed", FileSize.AutoFormat(totalCompressedSize), FileSize.AutoFormat(totalDecompressedSize));
                    }



                    featureBlockNumbers.Sort();
                    System.Text.StringBuilder featureBlockNumberString = new StringBuilder();
                    for (int i = 0; i < featureBlockNumbers.Count; i++)
                    {
                        featureBlockNumberString.Append(string.Format("{0:N0}", featureBlockNumbers[i]));
                        if (i < (featureBlockNumbers.Count - 1))
                        {
                            featureBlockNumberString.Append(", ");
                        }
                    }
                    this.featureBlockLabel.Text = featureBlockNumberString.ToString();
                }

                foreach (ColumnHeader clm in this.blockMapListView.Columns)
                {
                    clm.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize);
                    int headerWidth = clm.Width;
                    clm.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent);
                    int contentWidth = clm.Width;
                    clm.Width = Math.Max(headerWidth, contentWidth);
                }

                this.blockMapListView.ResumeLayout();
            }
            else
            {
                ClearDetailsControls();
            }
            */
        }

        private static string ConvertToHexString(int value)
        {
            string hexString = string.Format("{0:X}", value);
            int stringLen = hexString.Length / 4;
            if (hexString.Length % 4 != 0)
                stringLen++;
            stringLen *= 4;
            System.Text.StringBuilder newHexString = new System.Text.StringBuilder(hexString.PadLeft(stringLen, '0'));
            for (int i = 4; i < newHexString.Length; i += 4)
            {
                newHexString.Insert(i, ' ');
                i++;
            }
            return newHexString.ToString();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox about = new AboutBox();
            about.ShowDialog(this);
        }

        private void CloseVolumeFile()
        {
            if (this.volumeFile != null)
            {
                this.volumeFile.Dispose();
                this.volumeFile = null;
            }
            this.packageHistoryToolStripMenuItem.Enabled = false;
            this.closeToolStripMenuItem.Enabled = false;
            ClearDetailsControls();
            this.fileSystemTree.Nodes.Clear();
        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.CloseVolumeFile();
        }

        private void FormClosingHandler(object sender, FormClosingEventArgs e)
        {
            this.closeToolStripMenuItem.PerformClick();
        }

        private void exportToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            /*
            if (this.fileSystemTree.SelectedNode != null)
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.FileName = this.fileSystemTree.SelectedNode.Text;
                if (sfd.ShowDialog(this) == DialogResult.OK)
                {
                    DirectoryMapEntry entry = this.fileSystemTree.SelectedNode.Tag as DirectoryMapEntry;
                    if (entry != null)
                    {
                        this.volumeFile.ExportDirectoryEntry(entry, sfd.FileName);
                        MessageBox.Show("done!");
                    }
                }
            }
            */
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.closeToolStripMenuItem.PerformClick();
            this.Close();
        }

        private void packageHistoryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            /*
            if (this.volumeFile != null)
            {
                PackageHistoryForm phf = new PackageHistoryForm(this.volumeFile.ContentDescription);
                phf.ShowDialog(this);
            }
            */
        }
    }
}
